package com.wifi.a007.utile;

import android.content.SharedPreferences;
import android.database.CursorJoiner;
import android.location.Address;
import android.preference.PreferenceManager;
import android.provider.UserDictionary;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.StreamBitmapDataLoadProvider;
import com.bumptech.glide.util.ExceptionCatchingInputStream;
import com.google.gson.JsonObject;
import com.wifi.a007.LogPrint;
import com.wifi.a007.ViewName;
import com.wifi.a007.db.ArmWord;
import com.wifi.a007.db.Word;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;
import java.nio.channels.NonWritableChannelException;
import java.security.Principal;
import java.security.cert.CertificateNotYetValidException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.jar.Attributes;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/7/13.
 */

public class handleInternet {

    private  static String currentWord="";
    private  static boolean isArmWord=false;

    public static boolean handlWordResponse(String wordName,final String returnJson) {

        try {



            JSONObject jsonFirst = new JSONObject(returnJson);
            String status = jsonFirst.getString("status");
            if(!status.equals("0")){//查询失败或者中文

                LogPrint.echo("status is not 0 has someproblem");
                return  false;
            }
            Word  word= new Word();
            word.setWordName(wordName);
            JSONObject content=(JSONObject)jsonFirst.get("content");

            ///简单的先保存
            word.setAmeFayin(content.getString("ph_am"));
            word.setEngFayin(content.getString("ph_en"));
            word.setAmeMp3Url(content.getString("ph_am_mp3"));
            word.setEngMp3Url(content.getString("ph_en_mp3"));



            JSONArray jsonMeans = content.getJSONArray("word_mean");
            final StringBuilder stringBuilder=new StringBuilder();

            for(int i=0;i<jsonMeans.length();i++){

                String string = jsonMeans.getString(i);
                stringBuilder.append(string+"\n");
            }
            word.setWordmeans(stringBuilder.toString());

            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
            String dateString = formatter.format(currentTime);
            word.setFirstDate(dateString);
            word.setLastDate("0");




            word.save();
            LogPrint.echo(word+"save word success");





        } catch (Exception e) {

            e.printStackTrace();
        }

        return true;

    }

public static boolean  handlArmWordResponse(String name ,String value){

    if(value.equals("0")){

        return  false;
    }

    ArmWord armWord = new ArmWord();

    armWord.setArmName(name);
    armWord.setArmMeans(value);

    armWord.save();
    LogPrint.echo("save armWord success");


    return true;







}

///////////////////query
   public static void queryWord(String word){
        currentWord=word;
        List<Word> means = DataSupport.where("wordName = ? ",word).find(Word.class);

       if(means.size() >0){

           final String wordmeans=means.get(0).getWordmeans();

           ViewName.webView.post(new Runnable() {
               @Override
               public void run() {

                   LogPrint.toast(ViewName.mContext,wordmeans);

               }
           });






       }else{
           String address = "http://fy.iciba.com/ajax.php?a=fy&" + "f=auto&t=auto&w=" + word;
           queryFromServer(address);


       }




   }


    public static void queryArmWord(String word){

        currentWord=word;
        isArmWord=true;

        List<ArmWord> means = DataSupport.where("armName = ? ",word).find(ArmWord.class);

        if(means.size() >0){

            final String wordmeans=means.get(0).getArmMeans();

            ViewName.webView.post(new Runnable() {
                @Override
                public void run() {

                    LogPrint.toast(ViewName.mContext,wordmeans);

                }
            });


            isArmWord=false;



        }else{

            String address = "http://192.168.201.4/armSearch.php?armWord="+word;

            queryFromServer(address);


        }




    }




    public  static void  queryFromServer(final String address){




            HttpUtil.sendOkHttpGetRequest(address, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                    LogPrint.toast(ViewName.mContext,"网络请求失败");

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    if(isArmWord){
                        boolean result = handlArmWordResponse(currentWord,response.body().string());

                        if(result){

                            queryArmWord(currentWord);
                        }else{

                            ViewName.webView.post(new Runnable() {
                                @Override
                                public void run() {
                                    LogPrint.toast(ViewName.mContext,"暂时查询不到");
                                }
                            });


                        }

                    }else {
                        boolean result = handlWordResponse(currentWord, response.body().string());

                        if (result) {

                            queryWord(currentWord);
                        }else{

                            ViewName.webView.post(new Runnable() {
                                @Override
                                public void run() {
                                    LogPrint.toast(ViewName.mContext,"暂时查询不到");
                                }
                            });


                        }

                    }

                }
            });



    }




}
